/**
 * http://brucexx.iteye.com/
 */
package com.brucexx.wedding.service;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheFactory;
import javax.cache.CacheManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.brucexx.wedding.controller.AdminController;
import com.brucexx.wedding.dao.BaseModelDAO;
import com.brucexx.wedding.model.PicStore;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.jsr107cache.GCacheFactory;

/**
 * @author BruceXX email:brucest0078@gmail.com
 * 
 */
public class PicCacheService {

	private static final Log logger = LogFactory.getLog(PicCacheService.class);

	private static Cache cache;

	private PicCacheService() {

	}

	static {
		try {
			CacheFactory cacheFactory = CacheManager.getInstance()
					.getCacheFactory();
			Map props = new HashMap();
			props.put(GCacheFactory.EXPIRATION_DELTA, 3600);
			props.put(MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT, true);
			cache = cacheFactory.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static byte[] getContentByPicId(Long picId) {
		logger.info("load id[" + picId + "] cache");
		if (cache.containsKey(picId)) {
			return (byte[]) cache.get(picId);
		} else {
			Blob content = BaseModelDAO.loadById(picId, PicStore.class)
					.getShortContent();
			cache.put(picId, content.getBytes());
			return content.getBytes();
		}
	}

	public static byte[] getContentByPicIdAndType(long picId, String type) {
		String key = picId + "_" + type;
		if (cache.containsKey(key)) {
			return (byte[]) cache.get(key);
		} else {
			Blob content = BaseModelDAO.loadById(picId, PicStore.class)
					.getPicSnapShort();
			cache.put(key, content.getBytes());
			return content.getBytes();
		}

	}

}
